package com.haixiaoke.saas.lock.service.impl;

import java.time.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.DeviceLockConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.contract.domain.Contract;
import com.haixiaoke.saas.contract.service.IContractService;
import com.haixiaoke.saas.lock.domain.DeviceLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.mapper.LockFaceMapper;
import com.haixiaoke.saas.lock.service.IDeviceLockService;
import com.haixiaoke.saas.lock.service.ILockFaceService;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 锁人脸授权Service业务层处理
 * 
 * @author panda
 * @date 2025-06-26
 */
@Service
public class LockFaceServiceImpl implements ILockFaceService {
    @Autowired
    private LockFaceMapper lockFaceMapper;
    @Autowired
    private IDeviceLockService deviceLockService;
    @Autowired
    private LockDevicesService lockDevicesService;
    @Autowired
    private IUserConsumerService userConsumerService;
    @Autowired
    private IContractService contractService;

    /**
     * 查询锁人脸授权
     * 
     * @param faceId 锁人脸授权主键
     * @return 锁人脸授权
     */
    @Override
    public LockFace selectLockFaceByFaceId(Long faceId) {
        return lockFaceMapper.selectLockFaceByFaceId(faceId);
    }

    /**
     * 查询锁人脸授权列表
     * 
     * @param lockFace 锁人脸授权
     * @return 锁人脸授权
     */
    @Override
    public List<LockFace> selectLockFaceList(LockFace lockFace) {
        return lockFaceMapper.selectLockFaceList(lockFace);
    }

    /**
     * 新增锁人脸授权
     * 
     * @param lockFace 锁人脸授权
     * @return 结果
     */
    @Override
    public AjaxResult insertLockFace(LockFace lockFace) {
        AjaxResult ajaxResult = this.checkParam(lockFace);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        LocalDate nowLocalDate = LocalDate.now();
        ZonedDateTime zonedDateTime = lockFace.getAuthStartTime().toInstant().atZone(ZoneId.systemDefault());
        if (nowLocalDate.isAfter(zonedDateTime.toLocalDate())) {
            return AjaxResult.error("授权开始时间不可小于当前时间");
        }
        Date nowDate = DateUtils.getNowDate();
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockFace.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在，请联系管理员");
        }
        Contract contract = contractService.selectContractByHouseId(lock.getHouseId());
        if (ObjectUtil.isEmpty(contract)) {
            return AjaxResult.error("未有入住合同，不能添加用户");
        }
        if (StrUtil.equals(contract.getContactPhone(), lockFace.getUserPhone())) {
            lockFace.setUserName(contract.getContactName());
            lockFace.setLesseeFlag(DeviceLockConstants.LESSEE_FLAG_YES);
        }
        if (StrUtil.equals(DeviceLockConstants.AUTH_TIME_TYPE_LONG, lockFace.getAuthTimeType())) {
            LocalDateTime startTime = lockFace.getAuthStartTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            LocalDateTime endDateTime = startTime.plusYears(20)
                    .with(LocalTime.MAX); // 直接设置为当天的最后一刻
            lockFace.setAuthEndTime(Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        }
        if (StrUtil.isNotBlank(lockFace.getUserPhone()) && lockFace.getConUserId() == null) {
            UserConsumer user = userConsumerService.selectUserConsumerByPhone(lockFace.getUserPhone());
            if (ObjectUtil.isEmpty(user)) {
                user = new UserConsumer();
                user.setUserPhone(lockFace.getUserPhone());
                user.setNickName("未命名");
                user.setUserName(lockFace.getUserName());
                user.setCreateTime(nowDate);
                userConsumerService.insertUserConsumer(user);
            }
            lockFace.setConUserId(user.getUserId());
        }
        lockFace.setCreateTime(nowDate);
        String identification = lockDevicesService.getIdentification();
        lockFace.setIdentification(identification);
        if (StrUtil.isNotBlank(lockFace.getFaceImage())) {
            lockDevicesService.createLockFace(lockFace.getFaceImage(), lock.getLockMac(), identification, lockFace.getAuthStartTime(), lockFace.getAuthEndTime());
        }
        int result = lockFaceMapper.insertLockFace(lockFace);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 新增锁人脸授权
     *
     * @param lockFace 锁人脸授权
     * @return 结果
     */
    @Override
    public AjaxResult contractInsertLockFace(LockFace lockFace) {
        AjaxResult ajaxResult = this.checkParam(lockFace);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        Date nowDate = DateUtils.getNowDate();
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockFace.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在，请联系管理员");
        }
        if (StrUtil.equals(DeviceLockConstants.AUTH_TIME_TYPE_LONG, lockFace.getAuthTimeType())) {
            LocalDateTime startTime = lockFace.getAuthStartTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            LocalDateTime endDateTime = startTime.plusYears(20)
                    .with(LocalTime.MAX); // 直接设置为当天的最后一刻
            lockFace.setAuthEndTime(Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        }
        if (StrUtil.isNotBlank(lockFace.getUserPhone()) && lockFace.getConUserId() == null) {
            UserConsumer user = userConsumerService.selectUserConsumerByPhone(lockFace.getUserPhone());
            if (ObjectUtil.isEmpty(user)) {
                user = new UserConsumer();
                user.setUserPhone(lockFace.getUserPhone());
                user.setNickName("未命名");
                user.setUserName(lockFace.getUserName());
                user.setCreateTime(nowDate);
                userConsumerService.insertUserConsumer(user);
            }
            lockFace.setConUserId(user.getUserId());
        }
        lockFace.setCreateTime(nowDate);
        String identification = lockDevicesService.getIdentification();
        lockFace.setIdentification(identification);
        if (StrUtil.isNotBlank(lockFace.getFaceImage())) {
            lockDevicesService.createLockFace(lockFace.getFaceImage(), lock.getLockMac(), identification, lockFace.getAuthStartTime(), lockFace.getAuthEndTime());
        }
        int result = lockFaceMapper.insertLockFace(lockFace);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改锁人脸授权
     * 
     * @param lockFace 锁人脸授权
     * @return 结果
     */
    @Override
    public int updateLockFace(LockFace lockFace) {
        lockFace.setUpdateTime(DateUtils.getNowDate());
        return lockFaceMapper.updateLockFace(lockFace);
    }

    /**
     * 批量删除锁人脸授权
     * 
     * @param faceIds 需要删除的锁人脸授权主键
     * @return 结果
     */
    @Override
    public int deleteLockFaceByFaceIds(Long[] faceIds) {
        return lockFaceMapper.deleteLockFaceByFaceIds(faceIds);
    }

    /**
     * 删除锁人脸授权信息
     * 
     * @param faceId 锁人脸授权主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteLockFaceByFaceId(Long faceId) {
        LockFace lockFace = lockFaceMapper.selectLockFaceByFaceId(faceId);
        if (ObjectUtil.isEmpty(lockFace)) {
            return AjaxResult.error("锁人脸授权不存在，请联系管理员");
        }
        DeviceLock deviceLock = deviceLockService.selectDeviceLockByLockId(lockFace.getLockId());
        if (ObjectUtil.isEmpty(deviceLock)) {
            return AjaxResult.error("锁不存在，请联系管理员");
        }
        if (StrUtil.isNotBlank(lockFace.getFaceImage())) {
            lockDevicesService.removeFace(deviceLock.getLockMac(), lockFace.getIdentification());
        }
        int result = lockFaceMapper.deleteLockFaceByFaceId(faceId);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult checkParam(LockFace lockFace) {
        if (lockFace.getLockId() == null) {
            return AjaxResult.error("锁ID不能为空");
        }
        if (StrUtil.isBlank(lockFace.getUserPhone())) {
            return AjaxResult.error("手机号不能为空");
        }

        List<Map<String, Object>> maps = lockFaceMapper.checkNameAndPhone(lockFace);
        if (CollectionUtil.isNotEmpty(maps)) {
            for (Map<String, Object> map : maps) {
                if (Integer.parseInt(map.get("num").toString()) > 0) {
                    String type = map.get("type").toString();
                    switch (type) {
                        case "1":
                            return AjaxResult.error("名称已存在");
                        case "2":
                            return AjaxResult.error("该手机号已添加");
                    }
                }
            }
        }
        return null;
    }

    @Override
    public int insertBatchLockFace(List<LockFace> lockFaceList) {
        return lockFaceMapper.insertBatchLockFace(lockFaceList);
    }

    @Override
    public int deleteLockFaceByLockId(Long lockId) {
        return lockFaceMapper.deleteLockFaceByLockId(lockId);
    }

    @Override
    public AjaxResult editFaceImage(LockFace lockFace) {
        if (lockFace.getFaceId() == null) {
            return AjaxResult.error("用户标识不能为空");
        }
        LockFace faceByFaceId = lockFaceMapper.selectLockFaceByFaceId(lockFace.getFaceId());
        if (ObjectUtil.isEmpty(faceByFaceId)) {
            return AjaxResult.error("授权数据不存在");
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(faceByFaceId.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在，请联系管理员");
        }
        if (StrUtil.isBlank(lockFace.getFaceImage()) && StrUtil.isNotBlank(faceByFaceId.getFaceImage())) {
            lockDevicesService.removeFace(lock.getLockMac(), faceByFaceId.getIdentification());
        }
        if (StrUtil.isNotBlank(lockFace.getFaceImage())) {
            if (!StrUtil.equals(lockFace.getFaceImage(), faceByFaceId.getFaceImage())) {
                if (StrUtil.isNotBlank(faceByFaceId.getFaceImage())) {
                    lockDevicesService.updateLockFace(lockFace.getFaceImage(), lock.getLockMac(), faceByFaceId.getIdentification(), faceByFaceId.getAuthStartTime(), faceByFaceId.getAuthEndTime());
                } else {
                    lockDevicesService.createLockFace(lockFace.getFaceImage(), lock.getLockMac(), faceByFaceId.getIdentification(), faceByFaceId.getAuthStartTime(), faceByFaceId.getAuthEndTime());
                }
            }
        }
        lockFace.setUpdateTime(DateUtils.getNowDate());
        int result = lockFaceMapper.updateLockFaceByImage(lockFace);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public LockFace selectLockFaceByLockIdAndUserId(Long lockId, Long userId) {
        return lockFaceMapper.selectLockFaceByLockIdAndUserId(lockId, userId);
    }

    @Override
    public LockFace selectLockFaceByLockIdAndUserName(Long lockId, String userName) {
        return lockFaceMapper.selectLockFaceByLockIdAndUserName(lockId, userName);
    }

    @Override
    public List<LockFace> selectLockListByIdentifications(List<String> identifications) {
        return lockFaceMapper.selectLockListByIdentifications(identifications);
    }

    @Override
    public int checkUser(Long lockId) {
        return lockFaceMapper.checkUser(lockId);
    }
}
